package server

import (
	"context"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"longmen/server/config/global"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_sports"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
)

// 推荐主播
func (s *Server) RecommendAnchor(ctx context.Context, req *pb.RecommendAnchorReq) (*pb.RecommendAnchorResp, error) {
	params := map[string]interface{}{"status": 1}
	if req.Categoryid > 0 {
		params["categoryid"] = req.Categoryid
	}

	list, _ := cache.GetInstance().QueryLiveByCatAndStatus(int(req.Categoryid), 0, 1, 1, int(req.Size), true)

	var anchorIds []int
	if req.GetUid() > 0 {
		anchorIds = cache.GetUserAttentAnchorIds(int(req.Uid))
		global.Log.Debugf("anchorIds:%v", anchorIds)
	}

	tagQuery, _ := cache.GetAllTagCache()
	resp := new(pb.RecommendAnchorResp)

	var tempLiveIDs []int64
	for _, v := range list {
		if v.Ticket > 0 {
			tempLiveIDs = append(tempLiveIDs, v.Liveid)
		}
	}

	var ticketLogs []models_live.LiveTicketLog
	if req.Uid > 0 && len(tempLiveIDs) > 0 {
		ticketLogs = db_live.TicketINLives(int(req.Uid), tempLiveIDs)
	}
	var matchIDs []int
	for _, v := range list {
		isattent := 0
		for _, id := range anchorIds {
			if v.Anchorid == id {
				isattent = 1
				break
			}
		}

		//区域检测，暂时关闭
		userArea, _ := mysql.GetIpToArea(req.ClientIp)
		//检查屏蔽库是否返回动画直播
		v = db_live.Blocked(userArea, v)

		ticketPaid := 2
		//是否支付门票
		if len(ticketLogs) > 0 && v.Ticket > 0 {
			for _, l := range ticketLogs {
				if l.Liveid == v.Liveid {
					ticketPaid = 1
				}
			}
		}

		user, _ := s.GetUserById(v.Anchorid)
		uPoint := 0
		if user != nil {
			uPoint = user.Point
		}
		level, err := s.getUserLevel(uPoint) //用户经验值查询对应等级
		userLevel := 0
		if err == nil && level != nil {
			userLevel = int(level.Level)
		} else {
			global.Log.Errorf("RecommendAnchor err%v", err)
		}
		if req.Platform == 0 {
			v.Thumb = v.Thumb + "?" + _const.ThumbCropUrl + _const.PCThumbSize
		} else {
			v.Thumb = v.Thumb + "?" + _const.ThumbCropUrl + _const.MobileThumSize
		}
		tagInfo := getTag(v.Tag, tagQuery)
		live := &pb.RecommendAnchor{
			Anchorid:     uint32(v.Anchorid),
			Hot:          uint32(v.Hot),
			AnchorName:   v.AnchorName,
			Title:        v.Title,
			Thumb:        v.Thumb,
			ThumbY:       v.ThumbY,
			Isattent:     uint32(isattent),
			AnchorAvatar: v.AnchorAvatar,
			PullUrl:      v.PullUrl,
			PullFlvUrl:   v.PullFlvUrl,
			Animation:    int32(v.Animation),
			Status:       uint32(v.Status),
			CategoryId:   int32(v.Categoryid),
			MatchId:      int64(v.Matchid),
			TagId:        v.Tag,
			TagTitle:     "",
			TagColor:     "",
			TagPoint:     0,
			TagType:      0,
			Ticket:       int32(v.Ticket),
			TicketPaid:   int32(ticketPaid),
			Level:        int32(userLevel),
			ReplyVideo:   v.ReplyVideo,
			Comp:         common.StringPtr(""),
			CompLogo:     common.StringPtr(""),
			MatchTime:    common.Int64Ptr(0),
			Home:         common.StringPtr(""),
			HomeLogo:     common.StringPtr(""),
			Away:         common.StringPtr(""),
			AwayLogo:     common.StringPtr(""),
			SportId:      common.Int64Ptr(0),
		}
		if tagInfo != nil {
			live.TagTitle = tagInfo.Title
			live.TagColor = tagInfo.Color
			live.TagPoint = int32(tagInfo.Point)
			live.TagType = int32(tagInfo.Type)
		}
		matchIDs = append(matchIDs, v.Matchid)
		resp.RecommendAnchor = append(resp.RecommendAnchor, live)
	}
	matchMap := make(map[int]*models_sports.MatchTempSchedule)
	matchList := make([]*models_sports.MatchTempSchedule, 0)
	matchList, _ = db_sports.GetMatchTempScheduleByIds(matchIDs)
	for _, match := range matchList {
		matchMap[match.MatchId] = match
	}
	for _, live := range resp.RecommendAnchor {
		if match, ok := matchMap[int(live.MatchId)]; ok {
			live.Comp = common.StringPtr(match.Comp)
			live.CompLogo = common.StringPtr(match.CompLogo)
			live.MatchTime = common.Int64Ptr(match.MatchTime)
			live.Home = common.StringPtr(match.Home)
			live.HomeLogo = common.StringPtr(match.HomeLogo)
			live.Away = common.StringPtr(match.Away)
			live.AwayLogo = common.StringPtr(match.AwayLogo)
			live.SportId = common.Int64Ptr(int64(match.SportId))
		}
	}
	return resp, nil
}
